package LC;

import java.util.Scanner;

/**
 * Implement atoi to convert a string to an integer.
 * Hint: Carefully consider all possible input cases.
 * If you want a challenge, please do not see below and ask yourself what are the possible input cases.
 * Notes: It is intended for this problem to be specified vaguely (ie, no given input specs).
 * You are responsible to gather all the input requirements up front.
 */
public class LC_008_StringToInteger {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()) {
            String n = sc.nextLine();
            System.out.println(myAtoi(n));
        }
        sc.close();
    }

    //    discards all leading whitespaces
    //    sign of the number
    //    overflow
    //    invalid input
    private static int myAtoi(String str) {
        if (str.isEmpty()) return 0;

        int sign = 1, base = 0, i = 0, n = str.length();

        while (i < n && str.charAt(i) == ' ') ++i;

        if (str.charAt(i) == '+' || str.charAt(i) == '-')
            sign = (str.charAt(i++) == '+') ? 1 : -1;

        while (i < n && str.charAt(i) >= '0' && str.charAt(i) <= '9') {
            if (base > Integer.MAX_VALUE / 10 || (base == Integer.MAX_VALUE / 10 && str.charAt(i) - '0' > 7)) {
                return (sign == 1) ? Integer.MAX_VALUE : Integer.MIN_VALUE;
            }
            base = 10 * base + (str.charAt(i++) - '0');
        }
        return base * sign;
    }
}
